/*
 *  Copyright (c) 2018. 玺得（深圳）科技有限公司.保留所有权利. http://www.pi-top.com/ 玺得（深圳）科技有限公司保留所有代码著作权.如有任何疑问请访问官方网站与我们联系. 代码只针对特定需求定制编码，不得在未经允许或授权的情况下对外传播扩散.恶意传播者，法律后果自行承担. 本代码仅用于pps-cloud系统.
 */
package com.pitop.box.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baidu.fsg.uid.UidGenerator;
import com.pitop.box.dao.BoxDAO;
import com.pitop.box.dao.BoxItemDAO;
import com.pitop.box.entity.Box;
import com.pitop.box.entity.BoxItem;
import com.pitop.box.entity.BoxState;
import com.pitop.box.entity.BoxSyncState;
import com.pitop.core.base.BaseDAO;
import com.pitop.core.base.BaseSVImpl;
import com.pitop.core.entity.Page;
import com.pitop.core.exceptions.BaseException;
import com.pitop.core.exceptions.BoxException;
import com.pitop.sync.entity.SyncTraceModel;
import com.pitop.sync.entity.SyncTraceState;
import com.pitop.sync.service.SyncDataTraceSV;
import com.pitop.sync.service.SyncTraceSV;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("boxSV")
@Slf4j
public class BoxSVImpl extends BaseSVImpl<Box, Long> implements BoxSV {

    @Autowired
    private BoxDAO boxDAO;

    @Autowired
    private BoxItemDAO boxItemDAO;

    @Autowired
    private SyncTraceSV syncTraceSV;

    @Autowired
    private SyncDataTraceSV syncDataTraceSV;

    @Resource
    private UidGenerator uidGenerator;

    @Override
    protected BaseDAO getBaseDAO() {
        return boxDAO;
    }

    /**
     * 保存account对象
     *
     * @param entity 实体
     * @throws BaseException
     */
    @Override
    public void save(Box entity) throws BaseException {
        entity.setCode(String.valueOf(uidGenerator.getUID()));
        entity.setCreateTime(new Date());
        entity.setUpdateTime(new Date());
        super.save(entity);
    }

    /**
     * 加载一个对象Box
     *
     * @param id * @param code 编码* @param sn 箱SN
     * @return Box
     */
    @Override
    public Box load(Long id, String code, String sn) {
        if (id == null && code == null && sn == null) {
            throw new BoxException(BaseException.BaseExceptionEnum.Illegal_Param);
        }

        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("code", code);
        param.put("sn", sn);
        return boxDAO.load(param);
    }

    /**
     * 加载一个对象Box 通过id
     *
     * @param id
     * @return Box
     */
    @Override
    public Box loadById(Long id) {
        if (id == null) {
            throw new BoxException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        return boxDAO.loadById(id);
    }

    /**
     * 加载一个对象Box 通过code
     *
     * @param code 编码
     * @return Box
     */
    @Override
    public Box loadByCode(String code) {
        if (code == null) {
            throw new BoxException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        return boxDAO.loadByCode(code);
    }

    /**
     * 加载一个对象Box 通过sn
     *
     * @param sn 箱SN
     * @return Box
     */
    @Override
    public Box loadBySn(String sn) {
        if (sn == null) {
            throw new BoxException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        return boxDAO.loadBySn(sn);
    }

    /**
     * 加载一个对象Box 通过sn和工厂编码
     *
     * @param sn          箱SN
     * @param factoryCode 工厂编码
     * @return Box
     */
    @Override
    public Box loadBySnAndFactoryCode(String sn, String factoryCode) {
        return boxDAO.loadBySnAndFactoryCode(sn, factoryCode);
    }


    /**
     * 根据主键id,oldStates 共同更新 Box 的状态到newState状态
     *
     * @param id
     * @param newState  新状态
     * @param oldStates 旧状态集合
     */
    @Override
    public void updateStateById(Long id, BoxState newState, BoxState... oldStates) {
        if (id == null) {
            throw new BoxException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (newState == null) {
            throw new BoxException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (oldStates == null) {
            throw new BoxException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        String[] states = new String[oldStates.length];
        for (int i = 0; i < oldStates.length; i++) {
            states[i] = oldStates[i].name();
        }
        boxDAO.updateStateById(id, new Date(), newState.name(), states);
    }

    /**
     * 根据主键code,oldStates 共同更新 Box 的状态到newState状态
     *
     * @param code      编码
     * @param newState  新状态
     * @param oldStates 旧状态集合
     */
    @Override
    public void updateStateByCode(String code, BoxState newState, BoxState... oldStates) {
        if (code == null) {
            throw new BoxException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (newState == null) {
            throw new BoxException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (oldStates == null) {
            throw new BoxException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        String[] states = new String[oldStates.length];
        for (int i = 0; i < oldStates.length; i++) {
            states[i] = oldStates[i].name();
        }
        boxDAO.updateStateByCode(code, new Date(), newState.name(), states);
    }

    /**
     * 根据主键sn,oldStates 共同更新 Box 的状态到newState状态
     *
     * @param sn        箱SN
     * @param newState  新状态
     * @param oldStates 旧状态集合
     */
    @Override
    public void updateStateBySn(String sn, BoxState newState, BoxState... oldStates) {
        if (sn == null) {
            throw new BoxException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (newState == null) {
            throw new BoxException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (oldStates == null) {
            throw new BoxException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        String[] states = new String[oldStates.length];
        for (int i = 0; i < oldStates.length; i++) {
            states[i] = oldStates[i].name();
        }
        boxDAO.updateStateBySn(sn, new Date(), newState.name(), states);
    }

    /**
     * 根据主键id 更新 Box 的状态到另一个状态
     *
     * @param id
     * @param state 状态
     */
    @Override
    public void updateById(Long id, BoxState state) {
        if (id == null) {
            throw new BoxException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        boxDAO.updateById(id, state.name(), new Date());
    }

    /**
     * 根据主键code 更新 Box 的状态到另一个状态
     *
     * @param code  编码
     * @param state 状态
     */
    @Override
    public void updateByCode(String code, BoxState state) {
        if (code == null) {
            throw new BoxException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        boxDAO.updateByCode(code, state.name(), new Date());
    }

    /**
     * 根据主键sn 更新 Box 的状态到另一个状态
     *
     * @param sn    箱SN
     * @param state 状态
     */
    @Override
    public void updateBySn(String sn, BoxState state) {
        if (sn == null) {
            throw new BoxException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        boxDAO.updateBySn(sn, state.name(), new Date());
    }


    /**
     * 删除对象Box
     *
     * @param id * @param code 编码* @param sn 箱SN
     * @return Box
     */
    @Override
    public void delete(Long id, String code, String sn) {
        if (id == null && code == null && sn == null) {
            throw new BoxException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("code", code);
        param.put("sn", sn);
        boxDAO.delete(param);
    }


    /**
     * 查询Box分页
     *
     * @param box    对象
     * @param offset 查询开始行
     * @param limit  查询行数
     * @return List<Box>
     */
    @Override
    public List<Box> list(Box box, int offset, int limit) {
        if (offset < 0) {
            offset = 0;
        }

        if (limit < 0) {
            limit = Page.limit;
        }

        Map<String, Object> map = null;
        if (box != null) {
            map = JSON.parseObject(JSON.toJSONString(box, SerializerFeature.WriteDateUseDateFormat));
        } else {
            map = new HashMap<>();
        }
        return boxDAO.list(map, new RowBounds(offset, limit));
    }

    @Override
    public int count(Box box) {
        Map<String, Object> map = null;
        if (box != null) {
            map = JSON.parseObject(JSON.toJSONString(box, SerializerFeature.WriteDateUseDateFormat));
        } else {
            map = new HashMap<>();
        }
        return boxDAO.count(map);
    }

    /**
     * 查询Box分页
     *
     * @param id     * @param code  编码* @param sn  箱SN
     * @param offset 查询开始行
     * @param limit  查询行数
     * @return List<Box>
     */
    @Override
    public List<Box> list(Long id, String code, String sn, int offset, int limit) {
        if (offset < 0) {
            offset = 0;
        }

        if (limit < 0) {
            limit = Page.limit;
        }
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("code", code);
        param.put("sn", sn);
        return boxDAO.list(param, new RowBounds(offset, limit));
    }

    @Override
    public int count(Long id, String code, String sn) {
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("code", code);
        param.put("sn", sn);
        return boxDAO.count(param);
    }

    /**
     * todo 该版本存在一个问题：如果pps系统中删除了某个箱体，且在删除之前已经同步到了pps-cloud,则之后无法进行同步。
     * 从工厂端往云端同步箱库存数据
     * 1.验证数据合法性
     * 2.同步箱体数据：存在更新，不存在新增
     * 3.更新箱库存数据：判断pps-cloud中是否存在该产品，如果存在，查看对应的箱体sn和本次传过的来的箱体sn是否相同，不同则更新
     * 4.返回结果 true：成功，false：失败
     *
     * @param boxList 箱库存
     * @return boolean
     */
    @Override
    public boolean upwardsSyncBox(List<Box> boxList) {
        //1.验证数据合法性
        if (boxList == null || boxList.size() <= 0) {
            return false;
        }
        //2.同步箱体数据：存在更新，不存在新增
        List<BoxItem> boxItemList;
        Box boxFlag;
        BoxItem boxItemFlag;
        try {
            for (Box box : boxList) {
                boxFlag = boxDAO.loadBySnAndFactoryCode(box.getSn(), box.getFactoryCode());
                if (boxFlag == null) {
                    box.setSyncState(BoxSyncState.Synced.name());
                    boxDAO.insert(box);
                } else {
                    box.setSyncState(BoxSyncState.Synced.name());
                    boxDAO.update(box);
                }
                //记录同步追踪箱库存数据
                String desc = SyncTraceState.UpwardSyncBox.val + ",数据模型[" + SyncTraceModel.Box.name() + "],箱体编码-工厂编码[" + box.getCode() + "-" + box.getFactoryCode() + "]";
                String syncTraceCode = syncTraceSV.saveSyncTrace(box.getFactoryCode(), SyncTraceState.SyncSuccess.name(),
                        SyncTraceState.UpwardSync.name(), SyncTraceModel.Box.name(), box.getCode(), desc);
                //记录同步箱库存数据日志
                syncDataTraceSV.saveSyncDataTrace(syncTraceCode, box);


                //3.更新箱库存数据：判断pps-cloud中是否存在该产品，如果存在，查看对应的箱体sn和本次传过的来的箱体sn是否相同，不同则更新
                boxItemList = box.getBoxItems();
                if (boxItemList != null && boxItemList.size() > 0) {
                    for (BoxItem boxItem : boxItemList) {
                        boxItemFlag = boxItemDAO.loadByItemSn(boxItem.getItemSn());
                        //如果pps-cloud系统中不存在，直接插入新数据
                        if (boxItemFlag == null) {
                            boxItem.setFactoryCode(box.getFactoryCode());
                            boxItemDAO.insert(boxItem);
                        } else {
                            String boxSn = boxItemFlag.getBoxSn();
                            //如果pps-cloud存在，但是和本次同步时的箱体sn不同，则更新该条记录
                            if (!boxSn.equals(boxItem.getBoxSn())) {
                                boxItemFlag.setBoxSn(boxItem.getBoxSn());
                                boxItemDAO.update(boxItemFlag);
                            }
                        }
                        //记录同步追踪箱库存数据
                        desc = SyncTraceState.UpwardSyncBox.val + ",数据模型[" + SyncTraceModel.Box_Item.name() + "],箱体编码-工厂编码[" + box.getCode() + "-" + box.getFactoryCode() + "]";
                        syncTraceCode = syncTraceSV.saveSyncTrace(box.getFactoryCode(), SyncTraceState.SyncSuccess.name(),
                                SyncTraceState.UpwardSync.name(), SyncTraceModel.Box_Item.name(), box.getCode(), desc);
                        //记录同步箱库存数据日志
                        syncDataTraceSV.saveSyncDataTrace(syncTraceCode, boxItem);
                    }
                }
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    /**
     * 根据传入的箱体查询条件，统计该条件下所有的产品数量
     *
     * @param box
     * @return int
     */
    @Override
    public int countByBoxItem(Box box) {
        Map<String, Object> params;
        if (box != null) {
            params = JSON.parseObject(JSON.toJSONString(box, SerializerFeature.WriteDateUseDateFormat));
        } else {
            params = new HashMap<>();
        }
        return boxDAO.countByBoxItem(params);
    }
}
